package com.vipheyue.educationmp4.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.vipheyue.educationmp4.R;
import com.vipheyue.educationmp4.bean.MyUser;
import com.vipheyue.fastlib.utils.SharePreferencesUtil;

import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobInstallation;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobSMS;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.RequestSMSCodeListener;
import cn.bmob.v3.listener.UpdateListener;

public class LoginActivity extends BaseActivity {

    @Bind(R.id.iv_menu_left)
    ImageView iv_menu_left;
    @Bind(R.id.tv_menu_title)
    TextView tv_menu_title;
    @Bind(R.id.iv_menu_right)
    ImageView iv_menu_right;
    @Bind(R.id.et_phone)
    EditText et_phone;
    @Bind(R.id.et_passWord)
    EditText et_passWord;
    @Bind(R.id.et_codeSMS)
    EditText et_codeSMS;
    @Bind(R.id.tv_getSMS)
    TextView tv_getSMS;
    @Bind(R.id.btn_Send)
    Button btn_Send;
    public static String LOGINTIME = "LOGINTIME";
    // Storage Permissions
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);


// Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }

        RxPermissions.getInstance(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.INTERNET,
                        Manifest.permission.READ_PHONE_STATE)
                .subscribe(granted -> {
                    if (granted) {
                        // All requested permissions are granted
                        initView();
                    } else {
                        // At least one permission is denied
                        finish();
                    }
                });
    }

    private void initView() {
        tv_menu_title.setText("登录");
        iv_menu_left.setVisibility(View.INVISIBLE);
        MyUser userInfo = BmobUser.getCurrentUser(this, MyUser.class);
        if (userInfo != null) {
            String updateTime = SharePreferencesUtil.getSpString(LOGINTIME, "10", LoginActivity.this);
            Date curDate = new Date(System.currentTimeMillis());//获取当前时间
//            Logger.e(updateTime);
            if (judgmentDate(curDate.getTime(), Long.parseLong(updateTime))) {
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();
            }
        }
    }

    public static boolean judgmentDate(Long nowDate, Long update) {
        long cha = nowDate - update;
        if (cha < 0) {
            return false;
        }
        double result = cha * 1.0 / (1000 * 60 * 60);
        if (result <= 24*2) {
            return true;
        } else {
            return false;
        }
    }

    @OnClick({R.id.tv_getSMS, R.id.btn_Send})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_getSMS:
                tv_getSMS.setEnabled(false);
//                getBmobSms();
//                seGetSMSState();

                BmobQuery<BmobUser> query = new BmobQuery<BmobUser>();
                query.addWhereEqualTo("mobilePhoneNumber", et_phone.getText().toString().trim());
                query.findObjects(this, new FindListener<BmobUser>() {
                    @Override
                    public void onSuccess(List<BmobUser> object) {
                        if (object.size() != 0) {
                            getBmobSms();
                            seGetSMSState();
                        } else {
                            Toast.makeText(LoginActivity.this, "该学员没有注册本系统", Toast.LENGTH_SHORT).show();
                        }
                        tv_getSMS.setEnabled(true);
                    }

                    @Override
                    public void onError(int code, String msg) {
                        // TODO Auto-generated method stub
                        Toast.makeText(LoginActivity.this, "查询用户失败：" + msg, Toast.LENGTH_SHORT).show();
                        tv_getSMS.setEnabled(false);
                    }
                });

                break;
            case R.id.btn_Send:
                startLogin();
                break;
        }
    }

    private void startLogin() {
        BmobUser.loginBySMSCode(this, et_phone.getText().toString().trim(), et_codeSMS.getText().toString().trim(), new LogInListener<MyUser>() {
            @Override
            public void done(MyUser successUser, BmobException e) {
                if(successUser!=null){
                    MyUser myUser=new MyUser();
                    myUser.setInstallationId(BmobInstallation.getCurrentInstallation(getApplicationContext()).getInstallationId());
                    myUser.update(LoginActivity.this, successUser.getObjectId(),new UpdateListener() {
                        @Override
                        public void onSuccess() {
                            com.vipheyue.fastlib.utils.Log.e(new Gson().toJson(successUser));
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            finish();
                        }

                        @Override
                        public void onFailure(int i, String s) {
                            Toast.makeText(LoginActivity.this, "更新设备失败"+s, Toast.LENGTH_SHORT).show();
                        }
                    });



                }else {
                    Toast.makeText(LoginActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void getBmobSms() {
        BmobSMS.requestSMSCode(this, et_phone.getText().toString().trim(), "一键登录和注册模版", new RequestSMSCodeListener() {

            @Override
            public void done(Integer integer, BmobException e) {
                if (e == null) {//验证码发送成功
                    Toast.makeText(LoginActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                    Log.i("smile", "短信integer ：" + integer);//用于查询本次短信发送详情
                } else {
                    Toast.makeText(LoginActivity.this, "发送失败" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

        });
    }

    private void seGetSMSState() {
        tv_getSMS.setClickable(false);
        tv_getSMS.setBackgroundResource(R.drawable.common_background_yellow_corner_dark);
        CountDownTimer cdt = new CountDownTimer(30000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tv_getSMS.setText("请等待:" + millisUntilFinished / 1000 + "S");
            }

            @Override
            public void onFinish() {
                tv_getSMS.setClickable(true);
                tv_getSMS.setText("获取验证码");
                tv_getSMS.setBackgroundResource(R.drawable.common_background_yellow_corner);
            }
        };
        cdt.start();
    }

}
